import { getProducts, getProductsDeatail } from "@/api/products.js"
import { ref, watch, isRef, toRef } from "vue";
import { useRequest } from "vue-request";
import router from "@/router";


export const useProducts = () => {
    const productsList = ref([]);
    const loading = ref(false);
    const page = ref(1);

    const pageNum = ref(5);
    const total = ref(0);

    const filterCon = ref(null);



    //跳转详情页
    function showProductDetail(row) {
        // console.log(row);
        router.push({ name: 'detail', params: { id: row.id } });
        // router.push(`/home/products/${row.id}`);
    }

    const _getProducts = async () => {

        loading.value = true;
        //filter= {keywords:'小米',maxPrice:999}
        //...filterCon  keywords:'小米', maxPrice:999
        console.log({ ...filterCon.value });
        let result = await getProducts({ page: page.value, pageNum: pageNum.value, ...filterCon.value }).then(res => res.data);
        productsList.value = result.data;
        total.value = result.total;
        loading.value = false;
    }

    watch([page, filterCon], _getProducts, { immediate: true });

    //接收子组件传过来的submitForm e={"key":0}
    function onHandle(e) {
        if (Object.keys(e).length > 0) {
            filterCon.value = { ...e };
            console.log("filterList", filterCon.value);
        }
    }



    return {
        productsList,
        loading,
        page,
        pageNum,
        total,
        onHandle,
        showProductDetail
    }
}

export const useProductDetail = (id) => {
    //检查传进来的ids是否是响应式数据，如果不是，手动改成响应式
    // const id = isRef(ids) ? ids.value : toRef(ids);
    // console.log(id.value);
    //manual:true ：改成手动请求
    const { data, loading, run } = useRequest(getProductsDeatail, { manual: true });

    watch(id,()=>run(id),{immediate:true});

    console.log(data.value);


    return {
        data,
        loading
    }
}